package com.dingpeikeji.quickdeer.modules.base.web;

import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alipay.api.CreateDirectPayByUserApi;
import com.alipay.api.RefundFastpayByPlatformNopwdApi;
import com.alipay.model.CreateDirectPayByUserReq;
import com.alipay.model.RefundFastpayByPlatformNopwdReq;
import com.baidubce.services.lss.model.Video;
import com.dingpeikeji.quickdeer.core.common.config.Global;
import com.dingpeikeji.quickdeer.core.common.utils.CacheUtils;
import com.dingpeikeji.quickdeer.core.common.utils.StringUtils;
import com.dingpeikeji.quickdeer.core.common.web.BaseController;
import com.dingpeikeji.quickdeer.core.modules.driver.entity.TDrivers;
import com.dingpeikeji.quickdeer.core.modules.orders.entity.TOrders;
import com.dingpeikeji.quickdeer.core.modules.orders.entity.TOrdersOut;
import com.dingpeikeji.quickdeer.core.modules.orders.service.TOrdersOutService;
import com.dingpeikeji.quickdeer.core.modules.orders.service.TOrdersService;
import com.dingpeikeji.quickdeer.core.modules.payinfo.entity.TPayinfo;
import com.dingpeikeji.quickdeer.core.modules.realsche.entity.TRealsche;
import com.dingpeikeji.quickdeer.core.modules.realsche.service.TRealscheService;
import com.dingpeikeji.quickdeer.core.modules.site.entity.TSitedtl;
import com.dingpeikeji.quickdeer.core.modules.site.service.TSitedtlService;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.Office;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.User;
import com.dingpeikeji.quickdeer.core.modules.sys.utils.UserUtils;
import com.dingpeikeji.quickdeer.modules.realsche.service.FRealscheService;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.DemandsReact;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.FDemandsService;
import com.dingpeikeji.quickdeer.modules.sms.entity.Sms;
import com.dingpeikeji.quickdeer.modules.sms.service.SmsApi;
import com.dingpeikeji.quickdeer.modules.wx.common.web.OAuth;
import com.dingpeikeji.quickdeer.modules.wx.util.WxUtils;
import com.dingpeikeji.quickdeer.utils.JsonUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.tencent.WXPay;
import com.tencent.common.Configure;
import com.tencent.common.Signature;
import com.tencent.protocol.refund_protocol.RefundReqData;
import com.tencent.protocol.unifiedorder_protocol.UnifiedorderReqData;

import net.sf.json.JSONObject;

@Controller
@RequestMapping(value={"{channelType}/pay","{channelType}/pu/pay"})
public class PayController extends BaseController {
	
	@Autowired
	private FRealscheService fRealscheService;
	@Autowired
	private TRealscheService tRealscheService;
	@Autowired
	private TOrdersService tOrdersService;
	@Autowired
	private TSitedtlService tSitedtlService;
	@Autowired
	private TOrdersOutService tOrdersOutService;
	@Autowired
	private FDemandsService demandsService;
	
	/**
	 * 支付类型选择页面
	 * @return
	 */
	@RequestMapping("payWay") //  /f/pay/payWay?orderid=11000467
	public String payWay(@PathVariable String channelType, TOrders orders,String boardaddrfc,
			HttpServletRequest request,String offaddrfc,Model model){
		String viewPage = null;
		if (channelType.equals("f")) {
			viewPage = MessageFormat.format("modules/base/{0}PayWay", channelType); // 视图
		}else if (channelType.equals("a")) {
			viewPage = MessageFormat.format("modules/sys/{0}PayWay", channelType); // 视图
		}else {
			viewPage = MessageFormat.format("modules/base/{0}PayWay", channelType); // 视图
		}
		orders = fRealscheService.getOrders(orders.getOrderid().toString());
		
		// 分析锁定时间
		
		Date createDate = orders.getCreateDate();
		Long lockTime = 30*60*1000L; // 30分钟的毫秒数
		Date date = new Date(); // 当前系统时间
		Long leftTime = (createDate.getTime() + lockTime - date.getTime())/1000; // 锁定剩余时间
		if(leftTime > 0) { // 订单有效的时候才显示剩余时间
			model.addAttribute("minutes", leftTime/60);
			model.addAttribute("seconds", leftTime%60);
		}
		if(orders.getOrdertype().equals(TOrders.ORDER_TYPE_RENTPRODUCT_CUSTOM)) {
			TRealsche realsche = tRealscheService.get(orders.getRealscheid());
			DemandsReact react = demandsService.getDemandsReact(Integer.parseInt(realsche.getScheid()));
			model.addAttribute("react", react);
		}
		model.addAttribute("orders", orders); // 待支付的订单
		model.addAttribute("payWayType", TOrders.PAY_WAY_WXPAY); // 支付类型
		
		// 购买返程票时，返程日期要比出发日期多一天
		
		Calendar departdateCalendar = Calendar.getInstance();
		departdateCalendar.setTime(orders.getDepartdate()); // 出发日期肯定不为空
		departdateCalendar.add(Calendar.DATE, +1);
		SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd");
		model.addAttribute("departdateStr", ymd.format(departdateCalendar.getTime()));
		
		// 保存购票返程的出发地和目的地
		
		model.addAttribute("boardaddrfc", boardaddrfc);//返程的出发地
		model.addAttribute("offaddrfc", offaddrfc);//返程的目的地
		TSitedtl tSitedtlBoard = tSitedtlService.get(boardaddrfc);
		TSitedtl tSitedtlOff = tSitedtlService.get(offaddrfc);
		if(tSitedtlBoard!=null){
			model.addAttribute("boardaddrNamefc", tSitedtlBoard.getSitename());//获取返程出发地名称
		}
		if(tSitedtlOff!=null){
			model.addAttribute("offaddrNamefc", tSitedtlOff.getSitename());//获取返程目的地名称
		}

		return viewPage;//modules/base/wxPayWay
	}
	
	/**
	 * 支付订单页面
	 * @return
	 */
	@RequestMapping("pay")
	public String pay(@PathVariable String channelType, TOrders orders,String demandsid,String orderRemarks, Model model, RedirectAttributes redirectAttributes, HttpServletRequest request, HttpServletResponse response) throws Exception{
		String viewPageWx = MessageFormat.format("modules/base/{0}Wxpay", channelType); // 微信
		String viewPagePayWay = "redirect:/"+channelType+"/pay/payWay?orderid="+orders.getOrderid().toString(); // 支付方式页面
		//H5页面
		String type = request.getParameter("type");
		if ("notwx".equals(type)) {
			channelType = "h5";
		}
		// 校验数据
		List<String> messages = Lists.newArrayList(); // 消息
		fRealscheService.updateOrder(orders);
		orders = fRealscheService.getOrders(orders.getOrderid());
		model.addAttribute("orders", orders);
		if(!TOrders.STATUS_NO_PAY.equals(orders.getOrderstatus())){
			messages.add("该订单不可支付");
		}
		if(messages.isEmpty()) {
			if(orders.getPayway().equals(TOrders.PAY_WAY_ALIPAY)){ // 支付宝
				//商户订单号，商户网站订单系统中唯一订单号，必填
				String out_trade_no = "";
				for(int i=0;i<32-orders.getOrderid().length();i++){ // 补齐32位字符串
					out_trade_no+="0";
				}
				out_trade_no+=orders.getOrderid();
				//订单名称，必填
				String subject = orders.getOrdername();
				
				CreateDirectPayByUserReq req = new CreateDirectPayByUserReq(out_trade_no, subject, orders.getDueamount());
				new CreateDirectPayByUserApi().execute(req, request, response);
				return null;
			}
			if(orders.getPayway().equals(TOrders.PAY_WAY_WXPAY)){ // 微信
				if("f".equals(channelType)) {
					// 预支付，获取支付二维码
					BigDecimal b1 = new BigDecimal(orders.getDueamount());//1.00
					BigDecimal b2 = new BigDecimal("100");
					Float money = b1.multiply(b2).floatValue();//100.0
					String outTradeNo = "";
					for(int i=0;i<32-orders.getOrderid().length();i++){ // 补齐32位字符串
						outTradeNo+="0";
					}
					outTradeNo+=orders.getOrderid();//00000000000000000000000011000476
					UnifiedorderReqData unifiedorderReqData = new UnifiedorderReqData(orders.getOrdername()
							, outTradeNo
							, (int)money.floatValue()
							, Global.getConfig("wx.pay.ip")
							, Global.getConfig("wx.pay.notify_url")
							, "NATIVE");
					String result = WXPay.requestUnifiedorderService(unifiedorderReqData);
					logger.debug("微信预支付返回信息={}", result);
					Document doc = DocumentHelper.parseText(result);
					Element root = doc.getRootElement();			
					Element code_url = root.element("code_url");
					String textTrim = code_url.getTextTrim();//weixin://wxpay/bizpayurl?pr=1liXovt
					model.addAttribute("code_url", textTrim);
				}
				if("a".equals(channelType)) {
					// 预支付，获取支付二维码
					BigDecimal b1 = new BigDecimal(orders.getDueamount());//1.00
					BigDecimal b2 = new BigDecimal("100");
					Float money = b1.multiply(b2).floatValue();//100.0
					String outTradeNo = "";
					for(int i=0;i<32-orders.getOrderid().length();i++){ // 补齐32位字符串
						outTradeNo+="0";
					}
					outTradeNo+=orders.getOrderid();//00000000000000000000000011000476
					UnifiedorderReqData unifiedorderReqData = new UnifiedorderReqData(orders.getOrdername()
							, outTradeNo
							, (int)money.floatValue()
							, Global.getConfig("wx.pay.ip")
							, Global.getConfig("wx.pay.notify_url")
							, "NATIVE");
					String result = WXPay.requestUnifiedorderService(unifiedorderReqData);
					logger.debug("微信预支付返回信息={}", result);
					Document doc = DocumentHelper.parseText(result);
					Element root = doc.getRootElement();			
					Element code_url = root.element("code_url");
					String textTrim = code_url.getTextTrim();//weixin://wxpay/bizpayurl?pr=1liXovt
					model.addAttribute("code_url", textTrim);
				}
				if("wx".equals(channelType)) {
					// 预支付
					BigDecimal b1 = new BigDecimal(orders.getDueamount());
					BigDecimal b2 = new BigDecimal("100");
					Float money = b1.multiply(b2).floatValue();
					String outTradeNo = "";
					for(int i=0;i<32-orders.getOrderid().length();i++){ // 补齐32位字符串
						outTradeNo+="0";
					}
					outTradeNo+=orders.getOrderid();
					UnifiedorderReqData unifiedorderReqData = new UnifiedorderReqData(orders.getOrdername()
							, outTradeNo
							, (int)money.floatValue()
							, Global.getConfig("wx.pay.ip")
							, Global.getConfig("wx.pay.notify_url")
							, "JSAPI");
					User commonUser = (User)request.getSession().getAttribute(OAuth.FRONT_USER_IN_SESSION);
					unifiedorderReqData.setOpenid(commonUser.getWechatId());
					unifiedorderReqData.setSign("");
					unifiedorderReqData.setSign(Signature.getSign(unifiedorderReqData.toMap()));
					String result = WXPay.requestUnifiedorderService(unifiedorderReqData);
					logger.debug("返回的结果={}",result);
					Document doc = DocumentHelper.parseText(result);
					Element root = doc.getRootElement();			
					Element prepay_id = root.element("prepay_id");
					
					try {
						Map<String, Object> map = Maps.newHashMap();
						map.put("appId", Configure.getAppid());
						map.put("nonceStr", WxUtils.create_nonce_str());
						map.put("package", "prepay_id="+prepay_id.getTextTrim());
						map.put("signType", "MD5");
						map.put("timeStamp", System.currentTimeMillis() / 1000);
						model.addAllAttributes(map);
						model.addAttribute("prepay_id",  "prepay_id="+prepay_id.getTextTrim());
						model.addAttribute("signature",  Signature.getSign(map));
					} catch (Exception e) {
						String msg = root.element("return_msg").getTextTrim();
						if(!msg.equals("ok")){
							model.addAttribute("message", root.element("return_msg").getTextTrim());
						}
					}
				}
				if("h5".equals(channelType)) {
					// 预支付
					BigDecimal b1 = new BigDecimal(orders.getDueamount());
					BigDecimal b2 = new BigDecimal("100");
					Float money = b1.multiply(b2).floatValue();
					String outTradeNo = "";
					for(int i=0;i<32-orders.getOrderid().length();i++){ // 补齐32位字符串
						outTradeNo+="0";
					}
					outTradeNo+=orders.getOrderid();
					//获取用户真实ip
					String spbillCreateIp = request.getRemoteAddr();
					//场景信息
					UnifiedorderReqData unifiedorderReqData = new UnifiedorderReqData(orders.getOrdername()
							, outTradeNo
							, (int)money.floatValue()
							, spbillCreateIp
							, Global.getConfig("wx.pay.notify_url")
							, "MWEB");
					Map<String,Object> maps = new HashMap<String,Object>();
					Map<String, String> subMap = new HashMap<String, String>();
					subMap.put("type", "Wap");
					subMap.put("wap_url", "https://www.xiakeyueche.com");
					subMap.put("wap_name","霞客约车");
					maps.put("h5_info", subMap);
					JSONObject json = JsonUtils.mapToJson(maps);
					unifiedorderReqData.setScene_info(json.toString());
					unifiedorderReqData.setSign("");
					unifiedorderReqData.setSign(Signature.getSign(unifiedorderReqData.toMap()));
					String result = WXPay.requestUnifiedorderService(unifiedorderReqData);
					logger.debug("返回的结果={}",result);
					Document doc = DocumentHelper.parseText(result);
					Element root = doc.getRootElement();			
					Element mweb_url = root.element("mweb_url");
					String redirect_url = URLEncoder.encode("https://www.xiakeyueche.com/wx/orders/orderList?&type=notwx");
					try {
						model.addAttribute("mweb_url", mweb_url.getTextTrim()+"&redirect_url="+redirect_url);
						logger.debug("返回mweb_url的结果={}",mweb_url.getTextTrim()+"&redirect_url="+redirect_url);
					} catch (Exception e) {
						String msg = root.element("return_msg").getTextTrim();
						if(!msg.equals("ok")){
							model.addAttribute("message", root.element("return_msg").getTextTrim());
						}
					}
					return "modules/base/H5pay";
				}
				return viewPageWx;
			}
			// TODO 线下结算和其他的方式暂不考虑
			if(orders.getPayway().equals(TOrders.PAY_WAY_OFFLINE)){ // 线下支付,需要修改订单状态
				int id = Integer.parseInt(orders.getOrderid());
				fRealscheService.updateOrderOffline(id,orderRemarks.substring(1));//支付方式改为线下支付,状态已支付
				demandsService.updateState(demandsid);//TDemands.REACTSTATUS_DONE = "3"; // 已支付
				tRealscheService.updateState(orders.getRealscheid());//班次 未调度
				//发送短信
				Sms sendSms = new Sms();
				sendSms.setMobile(orders.getPayertel());
				sendSms.setContent("尊敬的"+orders.getContacts()+
							"先生/女士，您已成功预定："+orders.getOrdername()+
							"，请及时联系客服进行付款。祝您出行愉快！");
				try {
					SmsApi.sendSms(sendSms);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return "modules/sys/offlineOrder";
			}
		} 
		addMessage(redirectAttributes, messages.toArray(new String[]{}));
		redirectAttributes.addFlashAttribute("orders", orders);
		return viewPagePayWay;
	}

	/**
	 * 取消订单
	 * @return
	 */
	@RequestMapping("cancel")
	public String cancel(@PathVariable String channelType, TOrders orders, RedirectAttributes redirectAttributes, HttpServletRequest request){
		String viewPage = "redirect:/"+channelType+("wx".equals(channelType)?"/pu":"")+"/orders/orderList?repage"; // 视图
		String cancelid = null; // 取消人ID
		if("a".equals(channelType)) {
			cancelid = UserUtils.getUser().getId();
		}
		if("f".equals(channelType)) {
			User user = (User) request.getSession().getAttribute(FSysController.FRONT_USER_IN_SESSION);
			cancelid = user.getId();
		}
		if("wx".equals(channelType)) {
			// 微信的用户身份保存在session中
			User user = (User)request.getSession().getAttribute(OAuth.SESSION_PUBUSER);
			cancelid = user.getId();
		}
		TOrders ord=tOrdersService.get(orders.getOrderid());
		if(!ord.getOrderstatus().equals(TOrders.STATUS_NO_PAY)) {
			addMessage(redirectAttributes, "该订单不能取消");
		} else {
			String message = fRealscheService.cancelOrder(orders, cancelid);
			if(message == null){
				addMessage(redirectAttributes, "取消订单成功！");
			} else {
				addMessage(redirectAttributes, message);
			}
		}
		return viewPage;
	}
	
	/**
	 * 废除订单的删除
	 * @param channelType
	 * @param orders
	 * @param redirectAttributes
	 * @param request
	 * @return
	 */
	@RequestMapping("deleteOrder")
	public String deleteOrder(@PathVariable String channelType, TOrders orders, RedirectAttributes redirectAttributes, HttpServletRequest request){
		String viewPage = "redirect:/"+channelType+("wx".equals(channelType)?"/pu":"")+"/orders/orderList?repage"; // 视图
		TOrders order=tOrdersService.get(orders.getOrderid());
		tOrdersService.delete(order);
		return viewPage;
	}
	
	
	/**
	 * 生成微信支付的二维码
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("qrCode")
	public void qrCode(String code_url, HttpServletResponse response) throws Exception{
		int width = 300;
		int height = 300;
		String format = "png";
		Hashtable<EncodeHintType,String> hints = new Hashtable<EncodeHintType,String>();
		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
		BitMatrix bitMatrix = new MultiFormatWriter().encode(code_url, BarcodeFormat.QR_CODE, width, height, hints);
		
		response.setContentType("image/png"); // 设置返回内容格式
		OutputStream os = response.getOutputStream(); // 创建输出流
		MatrixToImageWriter.writeToStream(bitMatrix, format, os);
		os.flush();
		os.close();
	}
	/**
	 * 生成微信支付的二维码
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("backMoneyPage")
	public String backMoneyPage(TOrders orders, HttpServletResponse response,HttpServletRequest request,Model model) throws Exception{
		User user = (User) request.getSession().getAttribute(FSysController.FRONT_USER_IN_SESSION);
		if (user==null) {
			String contextPath = request.getContextPath()+"/login.jsp";
			response.sendRedirect(contextPath);
			return null;
		}
		TOrders torders = fRealscheService.getOrders(orders.getOrderid());
		if (torders.getDepartdate().before( new Date())) {
			request.getSession().setAttribute("mes", "已过发车时间,无法退款");
			return "redirect:/f/orders/orderList";
		}
		//计算时间差
		long dateDistance = getDatePoor(torders.getDepartdate(), new Date());
		//计算违约金
		double penalty = 0.0;
		if (dateDistance<=24) {
			//行程开始前 24 小时内,按费用总额的50%收取违约金
			penalty = Math.ceil(Double.parseDouble(torders.getDueamount())*0.5);
		}else if (dateDistance<=0) {
			//超过发车时间不可退款
			penalty = Math.ceil(Double.parseDouble(torders.getDueamount()));
		}else if(dateDistance<=72&&dateDistance>24){
			//行程开始前 72 小时至 24 小时,按费用总额的30%(普通用户)
			if (Office.FLAT_TYPE_SMALLCO.equals(user.getOffice().getFlatType())) {
				penalty = Math.ceil(Double.parseDouble(torders.getDueamount())*0.3);
			}else{//旅行商10%
				penalty = Math.ceil(Double.parseDouble(torders.getDueamount())*0.1);
			}
		}else {
			penalty = 0.0;
		}
		torders.setPenalty(penalty);
		model.addAttribute("torders", torders);
		return "/modules/base/cancellation";
	}
	
	public static long getDatePoor(Date endDate, Date nowDate) {
		 
	    long nh = 1000 * 60 * 60;
	    // 获得两个时间的毫秒时间差异
	    long diff = endDate.getTime() - nowDate.getTime();
	    // 计算差多少小时
	    long hour = diff / nh ;
	    return hour;
	}
	/**
	 * 退票
	 * @return
	 */
	@RequestMapping("backMoney")
	public String backMoney(@PathVariable String channelType, TOrders orders, RedirectAttributes redirectAttributes, HttpServletRequest request, HttpServletResponse response){
		String viewPage = null;
		if(channelType.equals("wx")){
			viewPage = MessageFormat.format("redirect:/wx/pu/orders/orderList?repage&orderstatus={1}", TOrders.STATUS_PAY); // 视图
		}
		if(channelType.equals("f")){
			viewPage = "redirect:/f/orders/orderList"; // 视图
		}
		TOrders torders = fRealscheService.getOrders(orders.getOrderid());
		// ==========>>数据校验
		List<String> messages = Lists.newArrayList(); // 消息
		boolean sendSms = false; // 是否发送短信
		if(messages.isEmpty()) {
			TPayinfo payinfo = torders.getPayinfo();
			if(payinfo!=null && payinfo.getDiscountid() != null){
				Map<String,Object> result = fRealscheService.proCmptReturn(orders);
				Integer returnflag = (Integer) result.get("returnflag");
				if(returnflag!=null&&returnflag==0){
					String payway = torders.getPayway();
					//批次号，必填，格式：当天日期[8位]+序列号[3至24位]，如：201603081000001
					String batch_no = new SimpleDateFormat("yyyyMMdd").format(new Date())+UUID.randomUUID().toString().replace("-", "").substring(0, 16);
					//退款笔数，必填，参数detail_data的值中，“#”字符出现的数量加1，最大支持1000笔（即“#”字符出现的数量999个）
					String batch_num = "1";
					Double money = (Double) result.get("returnmoney");
					//退款详细数据，必填，格式（支付宝交易号^退款金额^备注），多笔请用#隔开
					String detail_data = payinfo.getFlowno() // 流水号就是支付宝单号
							+"^"+money+"^"
							+torders.getPurchasenum()+","+torders.getChildnum(); // 退款数量
					if(payway.equals(TOrders.PAY_WAY_ALIPAY)){ // 支付宝支付
						String refund_date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
						try {
							RefundFastpayByPlatformNopwdReq req = new RefundFastpayByPlatformNopwdReq(batch_no, refund_date, batch_num, detail_data);
							new RefundFastpayByPlatformNopwdApi().execute(req, request, response);
							// 保存退款信息
							TOrdersOut orderOut = new TOrdersOut();
							orderOut.setOrderid(Integer.parseInt(torders.getOrderid()));
							orderOut.setBatchNo(batch_no);
							orderOut.setOutnum(Integer.parseInt(torders.getPurchasenum()));
							orderOut.setRtnmoney(money);
							orderOut.setOutchildnum(Integer.parseInt(torders.getChildnum()==null?"0":torders.getChildnum()));
							orderOut.setNotifyed(TOrdersOut.NOTIFED_NO);
							orderOut.setOutuserid(UserUtils.getUser().getId());
							orderOut.setRtnstatus(TOrdersOut.RTN_STATUS_FAIL);
							tOrdersOutService.save(orderOut);
							fRealscheService.proConfirmRtn(batch_no);
//							return null;
							messages.add("支付宝退票请求成功！");
							sendSms = true;
						} catch (Exception e) {
							messages.add("请求退款异常！");
						}
					}
					if(payway.equals(TOrders.PAY_WAY_WXPAY)){ // 微信支付
						String out_trade_no = "";
						for(int i=0;i<32-orders.getOrderid().length();i++){ // 补齐32位字符串
							out_trade_no+="0";
						}
						int moneyint = (int)(money*100);
						out_trade_no+=torders.getOrderid();
						RefundReqData refundReqData = new RefundReqData(""//payinfo.getFlowno()
								, out_trade_no, ""
								, batch_no
								, (int)(Double.valueOf(torders.getDueamount())*100)
								, moneyint
								, Configure.getMchid()
								, "CNY");
						try {
							if(moneyint != 0){
								String responseString = WXPay.requestRefundService(refundReqData);
								logger.debug("微信退款返回信息：{}",responseString);
							}
							// 保存退款信息
							TOrdersOut orderOut = new TOrdersOut();
							orderOut.setOrderid(Integer.parseInt(torders.getOrderid()));
							orderOut.setBatchNo(batch_no);
							orderOut.setOutnum(Integer.parseInt(torders.getPurchasenum()));
							orderOut.setRtnmoney(money);
							orderOut.setOutchildnum(Integer.parseInt(torders.getChildnum()==null?"0":torders.getChildnum()));
							orderOut.setNotifyed(TOrdersOut.NOTIFED_NO);
							orderOut.setOutuserid(UserUtils.getUser().getId());
							orderOut.setRtnstatus(TOrdersOut.RTN_STATUS_FAIL);
							tOrdersOutService.save(orderOut);
							fRealscheService.proConfirmRtn(batch_no);
							if(moneyint == 0){
								messages.add("收取手续费后，可退费用为0元！");
							} else {
								messages.add("微信退票请求成功！");
							}
							sendSms = true;
						} catch (Exception e) {
							logger.debug("微信退票异常信息", e);
							messages.add("请求退款异常！");
						}
					}
				} else {
					messages.add((String) result.get("returnmsg"));
				}
			} else {
				messages.add("订单暂未生效！");
			}
		}
		// 订车人申请退单成功后，收到平台短信
		if(sendSms){
			Sms sms = new Sms();
			sms.setMobile(torders.getPayertel());
			sms.setContent("【霞客约车】您购买的由"+torders.getOffice().getName()+"提供的用车订单（"+torders.getOrderid()+"）已取消，我们将根据预订规则将相应款项在3个工作日内返回您的支付账户。");
			try {
				SmsApi.sendSms(sms);
			} catch (Exception e) {
			}
		}
		addMessage(redirectAttributes, messages.toArray(new String[]{}));
		return viewPage;
	}
}
